package com.example.blueconn.utils;

import android.os.Handler;
import android.os.Looper;

import com.example.blueconn.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolUtils {
    private static final ExecutorService executors = Executors.newFixedThreadPool(3);
//    private static final ExecutorService executors = Executors.newSingleThreadExecutor();

    private static final Handler handler = new Handler(Looper.getMainLooper());

    //任务集合
    private static final List<Runnable> works = new ArrayList<>();

    private static final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            for (Runnable run : works) {
                run.run();
            }
            handler.postDelayed(this, Constant.DATA_REFRESH_TIME);
        }
    };

    public static void submit(Runnable runnable) {
//        new Thread(runnable).start();
        executors.submit(runnable);
    }

    public static void runOnUiThread(final Runnable runnable) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                runnable.run();
            }
        });
    }

    public static void runOnUiThreadDelay(final Runnable runnable, int delay) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                runnable.run();
            }
        }, delay);
    }

    public static void startTimerWork() {
        handler.postDelayed(runnable, Constant.DATA_REFRESH_TIME);
    }

    public static void stopTimerWork() {
        handler.removeCallbacks(runnable);
    }

    public static void postWork(Runnable run) {
        if (run != null) {
            works.add(run);
        }
    }
}
